import datetime
import json

from django.core.files.storage import FileSystemStorage
from django.db import connection
from django.http import JsonResponse
from django.shortcuts import render
from django.template.defaultfilters import title
from rest_framework.views import APIView
from rest_framework_simplejwt.tokens import RefreshToken

from app.utils.User import User


# Create your views here.
class UploadAvatarView(APIView):
    """
     处理⽤户头像上传请求的视图类
    """

    def post(self, request):
        file_obj = request.FILES['avatar']
        userId = request.POST.get('userId')
        # 创建一个文件系统存储实例，指定存储目录为'media/app_userAvatar/'
        fs = FileSystemStorage(location='media/app_userAvatar/')

        # 使用文件系统存储实例保存上传的头像文件
        # 参数 file_obj.name 是上传文件的名称
        # 参数 file_obj 是包含文件内容的文件对象
        # 方法 save 返回文件在服务器上的名称，这通常是在重命名文件或使用哈希值时很有用
        filename = fs.save(file_obj.name, file_obj)

        # 构造保存文件的URL
        # 方法 url 返回文件相对于存储目录的URL路径
        # 在这里，我们将这个路径与服务器的基础URL拼接起来，形成完整的文件访问URL

        print(filename)
        try:
            with connection.cursor() as cursor:
                sql = 'update user set head=%s,update_time=NOW() where id=%s'
                cursor.execute(sql, [filename, userId])
            return JsonResponse({'code': 200, 'msg': '上传成功', 'file_url': filename})
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'msg': '上传失败'})


class LoginView(APIView):
    def post(self, request):
        data = json.loads(request.body)
        username = data['username']
        password = data['password']
        print(username, password)
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM user WHERE username = %s AND password = %s", [username, password])
            result = cursor.fetchone()
            if result:
                cursor.execute("Update user set update_time=%s where id = %s", [datetime.datetime.now(), result[0]])
            result = {
                'id': result[0],
                'username': username,
                'password': password,
            }
            if result:
                user = User(result)

                refresh_token = RefreshToken.for_user(user)
                access_token = str(refresh_token.access_token)

                return JsonResponse({"code": 200,
                                     "message": "登录成功",
                                     "token": access_token,
                                     "refresh_token": str(refresh_token),
                                     "userInfo": {
                                         "id": user.id,
                                         "username": username,
                                         "password": password
                                     }
                                     })
            else:
                return JsonResponse({'message': 'Invalid credentials'})


class GetMenuView(APIView):
    def get(self, request):
        with connection.cursor() as cursor:
            cursor.execute("SELECT * FROM `menu`")
            menus = cursor.fetchall()
            print(menus)
            menu_list = []
            for menu in menus:
                menu_list.append({
                    "id": menu[0],
                    "title": menu[1],
                    "url": menu[2],
                    "icon": menu[3],
                    "parent_id": menu[4]
                })
            menu_dict = {menu['id']: menu for menu in menu_list}
            processed_menu_ids = set()  # 用于跟踪已处理的菜单项 ID
            nested_menus = {}  # 用于存储嵌套结构

            for menu_id, menu in menu_dict.items():
                if menu_id in processed_menu_ids:
                    continue  # 如果已经处理过，则跳过

                parent_id = menu.get('parent_id')
                if parent_id is not None:
                    parent_menu = nested_menus.setdefault(parent_id, menu_dict[parent_id])
                    if 'children' not in parent_menu:
                        parent_menu['children'] = []
                    parent_menu['children'].append(menu)
                    processed_menu_ids.add(menu_id)  # 标记为已处理
                else:
                    # 对于没有父级的菜单项，直接添加到嵌套结构中
                    nested_menus[menu_id] = menu
                    processed_menu_ids.add(menu_id)  # 标记为已处理（虽然对于顶级菜单项这不是必需的）

            # 将嵌套结构转换为列表（如果需要）
            nested_menu_list = list(nested_menus.values())
            print(nested_menu_list)
            return JsonResponse({"code": 200, 'menu_list': nested_menu_list})


class GetUserInfo(APIView):
    def post(self, request):
        data = json.loads(request.body)
        pageNum = data['pageNum']
        pageSize = data['pageSize']
        query = data['query']
        like_param = f"%{query}%"
        with connection.cursor() as cursor:
            if query != '':
                cursor.execute("SELECT * FROM user where username Like %s LIMIT %s, %s",
                               [like_param, (pageNum - 1) * pageSize, pageSize])
            else:
                cursor.execute("SELECT * FROM user LIMIT %s, %s", [(pageNum - 1) * pageSize, pageSize])
            users = cursor.fetchall()
            cursor.execute("SELECT COUNT(*) FROM user WHERE username LIKE %s",
                           [like_param])
            total = cursor.fetchone()[0]
            print(users)
            column_names = ['id', 'head', 'username', 'password', 'email', 'status', 'balance', 'role', 'create_time',
                            'update_time', 'sex']  # 根据你的表结构调整字段名
            # 将查询结果转换为字典
            user_dict = [dict(zip(column_names, row)) for row in users]
            print(user_dict)
            return JsonResponse({"code": 200, 'userInfo': user_dict, 'total': total})

    def get(self, request):
        userId = request.GET.get('userId')
        print(userId)
        with connection.cursor() as cursor:
            cursor.execute("SELECT username,password,email,sex FROM user where id = %s", [userId])
            user = cursor.fetchone()
            column_names = ['username', 'password', 'email', 'sex']
            user = dict(zip(column_names, user))
            print(user)
            return JsonResponse({"code": 200, 'userInfo': user})


class UpdateUserInfo(APIView):
    def put(self, request):
        data = json.loads(request.body)
        print(data)
        userId = data['userId']
        username = data['userInfo']['username']
        password = data['userInfo']['password']
        email = data['userInfo']['email']
        sex = data['userInfo']['sex']
        print(userId, username, password, email, sex)
        with connection.cursor() as cursor:
            cursor.execute("Update user set username=%s,password=%s,email=%s,sex=%s where id = %s",
                           [username, password, email, sex, userId])
            return JsonResponse({"code": 200, 'message': '修改成功'})

    def post(self, request):
        data = json.loads(request.body)
        print(data)
        username = data['username']
        password = data['password']
        email = data['email']
        sex = data['sex']
        with connection.cursor() as cursor:
            cursor.execute("insert into user(username, password, email,sex,create_time) values (%s,%s,%s,%s,%s)",
                           [username, password, email, sex, datetime.datetime.now()])
        return JsonResponse({"code": 200, 'message': '添加成功'})


class UpdateUserStatus(APIView):
    def post(self, request):
        data = json.loads(request.body)
        userId = data['id']
        status = data['status']
        print(userId, status)
        with connection.cursor() as cursor:
            cursor.execute("Update user set status=%s where id = %s", [status, userId])
            return JsonResponse({"code": 200, 'message': '修改成功'})


class DeleteUser(APIView):
    def delete(self, request):
        userId = request.GET.get('userId')
        print(userId)
        with connection.cursor() as cursor:
            cursor.execute("delete from user where id = %s", [userId])
            return JsonResponse({"code": 200, 'message': '删除成功'})


class ResetPassword(APIView):
    def put(self, request):
        data = json.loads(request.body)
        userId = data['userId']
        print(userId)
        with connection.cursor() as cursor:
            cursor.execute('Update user set password=%s where id = %s', ["123456", userId])
            return JsonResponse({"code": 200, 'message': '重置成功'})


class DeleteUsers(APIView):
    def delete(self, request):
        userIds = request.GET.get('userIds').split(',')
        print(userIds)
        with connection.cursor() as cursor:
            for userId in userIds:
                cursor.execute("delete from user where id = %s", [int(userId)])

            return JsonResponse({"code": 200, 'message': '删除成功'})


class GetStoreList(APIView):
    def get(self, request):
        pageNum = int(request.GET.get('pageNum'))
        pageSize = int(request.GET.get('pageSize'))
        query = request.GET.get('query')
        print(type(pageNum), type(pageSize), query)
        like_param = f"%{query}%"
        with connection.cursor() as cursor:
            if query != '':
                cursor.execute(
                    "SELECT store.id,store.img,store.name,store.rate,store.sale,store.price1,store.price2,title.title,store.create_time FROM store,title where store.title_id=title.id and name Like %s LIMIT %s, %s",
                    [like_param, (pageNum - 1) * pageSize, pageSize])
            else:
                cursor.execute(
                    "SELECT store.id,store.img,store.name,store.rate,store.sale,store.price1,store.price2,title.title,store.create_time FROM store,title where title.id=store.title_id LIMIT %s, %s",
                    [(pageNum - 1) * pageSize, pageSize])

            stores = cursor.fetchall()
            cursor.execute("SELECT COUNT(*) FROM store")
            total = cursor.fetchone()[0]
            column_names = ['id', 'img', 'name', 'rate', 'sale', 'price1', 'price2', 'storeType', 'create_time']
            store_dict = [dict(zip(column_names, row)) for row in stores]
            print(store_dict)
            return JsonResponse({"code": 200, 'storeInfo': store_dict, 'total': total})


class GetStoreInfo(APIView):
    def get(self, request):
        storeId = request.GET.get('storeId')
        print(storeId)
        with connection.cursor() as cursor:
            cursor.execute(
                "SELECT store.img,store.name,store.rate,store.sale,store.price1,store.price2,store.create_time,title.title FROM store,title where store.title_id=title.id and store.id = %s",
                [storeId])
            store = cursor.fetchone()
            column_names = ['img', 'name', 'rate', 'sale', 'price1', 'price2', 'create_time', 'storeType']
            store = dict(zip(column_names, store))
            return JsonResponse({"code": 200, 'storeInfo': store})


class UpdateStoreInfo(APIView):
    def put(self, request):
        data = json.loads(request.body)
        storeId = data['storeId']
        name = data['storeInfo']['name']
        price1 = data['storeInfo']['price1']
        price2 = data['storeInfo']['price2']
        storeType = data['storeInfo']['storeType']
        with connection.cursor() as cursor:
            cursor.execute("select id from title where title=%s", [storeType])
            result = cursor.fetchone()
            if result:
                title_id = result[0]
                cursor.execute("Update store set name=%s,price1=%s,price2=%s,title_id=%s where id = %s",
                               [name, price1, price2, title_id, storeId])
                return JsonResponse({"code": 200, 'message': '修改成功'})
            else:
                cursor.execute("insert into title(title) values (%s)", [storeType])
                cursor.execute("select id from title where title=%s",
                               [storeType])
                result = cursor.fetchone()
                title_id = result[0]
                cursor.execute("Update store set name=%s,price1=%s,price2=%s,title_id=%s where id = %s",
                               [name, price1, price2, title_id, storeId])
            return JsonResponse({"code": 200, 'message': '修改成功'})

    def post(self, request):
        data = json.loads(request.body)
        name = data['name']
        price1 = data['price1']
        price2 = data['price2']
        storeType = data['storeType']
        with connection.cursor() as cursor:
            cursor.execute("select id from title where title=%s",
                           [storeType])
            result = cursor.fetchone()
            if result:
                title_id = result[0]
                cursor.execute("Insert into store(name,price1,price2,title_id,create_time) values (%s,%s,%s,%s,%s)",
                               [name, price1, price2, title_id, datetime.datetime.now()])
                return JsonResponse({"code": 200, 'message': '添加成功'})
            else:
                cursor.execute("insert into title(title) values (%s)", [storeType])
                cursor.execute("select id from title where title=%s",
                               [storeType])
                title_id = cursor.fetchone()[0]
                cursor.execute("insert into store(name,price1,price2,title_id,create_time) values (%s,%s,%s,%s,%s)",
                               [name, price1, price2, title_id, datetime.datetime.now()])
                return JsonResponse({"code": 200, 'message': '添加成功'})


class DeleteStore(APIView):
    def delete(self, request):
        storeId = request.GET.get('storeId')
        print(storeId)
        with connection.cursor() as cursor:
            cursor.execute("delete from store where id = %s", [storeId])
            return JsonResponse({"code": 200, 'message': '删除成功'})


class DeleteStores(APIView):
    def delete(self, request):
        storeIds = request.GET.get('storeIds').split(',')
        print(storeIds)
        with connection.cursor() as cursor:
            for storeId in storeIds:
                cursor.execute("delete from store where id = %s", [int(storeId)])
            return JsonResponse({"code": 200, 'message': '删除成功'})


class GetCommentList(APIView):
    def get(self, request):
        pageNum = int(request.GET.get('pageNum'))
        pageSize = int(request.GET.get('pageSize'))
        query = request.GET.get('query')
        print(query)
        like_param = f"%{query}%"
        with connection.cursor() as cursor:
            if query != '':
                cursor.execute(
                    'SELECT comments.id,user.username,comments.rate,comments.create_time,store.name AS store_name,comments.content FROM comments JOIN user ON comments.user_id = user.id JOIN store ON comments.store_id = store.id WHERE user.username LIKE %s OR comments.content LIKE %s or store.name like %s LIMIT %s, %s',
                    [like_param, like_param,like_param, (pageNum - 1) * pageSize, pageSize])
            else:
                cursor.execute(
                    "SELECT comments.id,user.username,comments.rate,comments.create_time,store.name,comments.content FROM comments,user,store where store.id=comments.store_id and comments.user_id=user.id LIMIT %s, %s",
                    [(pageNum - 1) * pageSize, pageSize])

            comments = cursor.fetchall()
            print(comments)
            cursor.execute("SELECT COUNT(*) FROM comments")
            total = cursor.fetchone()[0]
            column_names = ['id', 'username', 'rate', 'create_time', 'storeName', 'content']
            comments_dict = [dict(zip(column_names, row)) for row in comments]
            return JsonResponse({"code": 200, 'commentList': comments_dict, 'total': total})


class DeleteComment(APIView):
    def delete(self, request):
        commentId = request.GET.get('commentId')
        print(commentId)
        with connection.cursor() as cursor:
            cursor.execute("delete from comments where id = %s", [commentId])
            return JsonResponse({"code": 200, 'message': '删除成功'})


class DeleteComments(APIView):
    def delete(self, request):
        commentIds = request.GET.get('commentIds').split(',')
        print(commentIds)
        with connection.cursor() as cursor:
            for commentId in commentIds:
                cursor.execute("delete from comments where id = %s", [int(commentId)])
            return JsonResponse({"code": 200, 'message': '删除成功'})


class GetOrderList(APIView):
    def get(self, request):
        pageNum = int(request.GET.get('pageNum'))
        pageSize = int(request.GET.get('pageSize'))
        query = request.GET.get('query')
        like_param = f"%{query}%"
        with connection.cursor() as cursor:
            if query != '':
                cursor.execute(
                    'SELECT `order`.id,`order`.order_number,`order`.totalPrice,`order`.address_id,`order`.order_time,shopcar.goods_num,dishes.price,dishes.name,dishes.img,order_status.status,`order`.status '
                    'FROM `order`,shopcar,dishes,`address`,order_shopcar,order_status '
                    'WHERE `order`.id = order_shopcar.order_id and order_shopcar.shopcar_id=shopcar.id '
                    'and shopcar.dishes_id = dishes.id and `address`.id = `order`.address_id and order_status.order_status = `order`.status and `order`.order_number like %s limit %s,%s',
                    [like_param,(pageNum - 1) * pageSize, pageSize])
            else:
                cursor.execute(
                    'SELECT `order`.id,`order`.order_number,`order`.totalPrice,`order`.address_id,`order`.order_time,shopcar.goods_num,dishes.price,dishes.name,dishes.img,order_status.status,`order`.status '
                    'FROM `order`,shopcar,dishes,`address`,order_shopcar,order_status '
                    'WHERE `order`.id = order_shopcar.order_id and order_shopcar.shopcar_id=shopcar.id '
                    'and shopcar.dishes_id = dishes.id and `address`.id = `order`.address_id and order_status.order_status = `order`.status limit %s,%s',
                    [(pageNum - 1) * pageSize, pageSize])
            orders = cursor.fetchall()
            print(orders)
            cursor.execute('SELECT COUNT(*) FROM `order`')
            total = cursor.fetchone()[0]
            column_names = ['id', 'orderNumber', 'totalPrice', 'addressId', 'order_time', 'goodsNum', 'price',
                            'name', 'img', 'status1', 'status2']
            orders_dict = [dict(zip(column_names, row)) for row in orders]
            return JsonResponse({"code": 200, 'orderList': orders_dict, 'total': total})


class GetOrderDetail(APIView):
    def get(self, request):
        try:
            # 获取 orderId 参数
            orderId = int(request.GET.get('orderId'))
            print(orderId)

            # 执行查询
            with connection.cursor() as cursor:
                cursor.execute(
                    '''
                    SELECT 
                        `order`.id AS order_id,
                        `order`.order_number,
                        `order`.totalPrice,
                        `order`.address_id,
                        `order`.order_time,
                        `order`.status AS order_status,
                        shopcar.goods_num,
                        dishes.price AS dish_price,
                        dishes.name AS dish_name,
                        dishes.img AS dish_img,
                        order_status.status AS status_description
                    FROM 
                        `order` 
                    JOIN 
                        order_shopcar ON `order`.id = order_shopcar.order_id 
                    JOIN 
                        shopcar ON order_shopcar.shopcar_id = shopcar.id 
                    JOIN 
                        dishes ON shopcar.dishes_id = dishes.id 
                    JOIN 
                        order_status ON `order`.status = order_status.order_status 
                    WHERE 
                        `order`.id = %s
                    ''',
                    [orderId]
                )

                # 获取查询结果
                data = cursor.fetchall()

                # 将结果转为字典
                column_names = [
                    'order_id', 'order_number', 'totalPrice', 'address_id',
                    'order_time', 'order_status', 'goods_num', 'dish_price',
                    'dish_name', 'dish_img', 'status_description'
                ]
                data = [dict(zip(column_names, row)) for row in data]

                print(data)

            # 返回 JSON 响应
            return JsonResponse({'code': 200, 'info': '查询成功', 'data': data})

        except Exception as e:
            print(f"Error: {e}")
            return JsonResponse({'code': 500, 'info': '查询失败', 'error': str(e)})
